<template>
  <div>
    <el-card class="box-card">
      <Bar>
        <span class="bar-span">订单详情</span>
      </Bar>
      <!-- 订单头部 -->
      <div class="card-header mt-2">
        <div>
          <span>订单编号：{{ customerInfo.order_number }}</span>
          <span class="ml-4">录单时间：{{ customerInfo.record_time }}</span>
        </div>
        <el-tag type="warning">{{ order_status }}</el-tag>
      </div>

      <!-- 客户信息 -->
      <el-descriptions title="客户信息" :column="2" border class="mt-4">
        <el-descriptions-item label="客户姓名">{{ customerInfo.customer_name }}</el-descriptions-item>
        <el-descriptions-item label="客户电话">{{ customerInfo.phone }}</el-descriptions-item>
        <el-descriptions-item label="客户地址" :span="2">{{ customerInfo.address }}</el-descriptions-item>
        <el-descriptions-item label="客户类型">{{ customerInfo.customer_type }}</el-descriptions-item>
        <el-descriptions-item label="房间属性">{{ customerInfo.room_attributes }}</el-descriptions-item>
        <el-descriptions-item label="服务类型">{{ customerInfo.service_type }}</el-descriptions-item>
        <el-descriptions-item label="服务总价">{{ customerInfo.price }}</el-descriptions-item>
        <el-descriptions-item label="风控金">{{ customerInfo.risk_money }}</el-descriptions-item>
        <el-descriptions-item label="期望时间">{{ customerInfo.expected_time }}</el-descriptions-item>
        <el-descriptions-item label="客户标签">
          <el-tag type="success" v-for="(tag, index) in customerInfo.tags" :key="index" class="mr-2">
            {{ tag }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="备注">{{ customerInfo.remark }}</el-descriptions-item>
      </el-descriptions>

      <!-- 上门时间 -->
      <el-card class="mt-4" shadow="never">
        <template #header>
          <div class="card-title">上门时间</div>
        </template>
        <div class="time-selection">
          <div class="selected-time">
            <span>已选日期：{{ getSelectedDate }}</span>
            <span class="ml-4">已选档期：{{ getSelectedTime }}</span>
          </div>
          <div class="mt-2">
            <span class="text-sm mr-5">请选择档期:</span>
            <el-radio-group v-model="selectTimeResult" size="large">
              <el-radio value="上午8:00~10:00" border>上午8:00~10:00</el-radio>
              <el-radio value="上午10:30~12:30" border>上午10:30~12:30</el-radio>
              <el-radio value="下午2:00~4:00" border>下午2:00~4:00</el-radio>
              <el-radio value="下午4:30~6:30" border>下午4:30~6:30</el-radio>
            </el-radio-group>
          </div>
        </div>
      </el-card>

      <!-- 服务员工表格 -->
      <el-card class="mt-4" shadow="never">
        <template #header>
          <div class="card-title">服务员工</div>
        </template>
        <el-table 
          :data="staffSelectStore.gridData" 
          style="width: 100%"
          ref="tableRef"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="200" />
          <el-table-column type="index" label="序号" width="300" />
          <el-table-column prop="name" label="员工姓名" width="300" />
          <el-table-column prop="distance" label="与上一单距离" width="400">
            <template #default="scope">
              {{ scope.row.distance }}
            </template>
          </el-table-column>
          <el-table-column label="距离详情" min-width="200">
            <template #default="scope">
              <el-button type="primary" link @click="showDistanceDetail(scope.row)">
                查看详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 确认按钮 -->
      <div class="mt-4 text-right">
        <el-button type="primary" size="large" @click="handleConfirmOrder">确认订单</el-button>
      </div>

      <!-- 地图弹窗 -->
      <el-dialog align-center v-model="staffSelectStore.mapDetail" width="850" class="h-140">
        <t-map mode="orderInfo"></t-map>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup lang="ts" name="orderDetail">
import { computed, onMounted, reactive, ref, defineAsyncComponent, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import Bar from '@/components/Bar.vue'
import { useRoute, useRouter } from 'vue-router'
import instance from '@/api';
import { useStaffSelectStore } from '@/stores/useStaffSelectStore';
import { useStaffStore } from '@/stores/useStaffStore';
const TMap = defineAsyncComponent(() => import('@/components/TMap.vue'))
const staffSelectStore = useStaffSelectStore()
const route = useRoute();
const router = useRouter();
const id = route.params.id; // 直接获取 id
const selectTimeResult = ref('上午8:00~10:00')

// 客户信息
const customerInfo = reactive({
  customer_name:'',
  address:'',
  phone:'',
  customer_type:'',
  room_attributes:'',
  service_type:'', 
  price:'',
  risk_money:'',
  expected_time:'',
  tags:[],
  remark:'',
  record_time:'',
  order_number:'',
  arrival_time:'',
  service_staff:'',
  pay_status:-1,
  staffIds: [] as number[]
})
//订单状态
const order_status = computed(() => {
  const { arrival_time, service_staff, pay_status } = customerInfo
  if(!pay_status && (arrival_time && service_staff)) return "未收款已派单"
  else if(pay_status && (arrival_time && service_staff)) return "已收款已派单"
  else if(!pay_status && !(arrival_time && service_staff)) return "未收款未派单"
  else if(pay_status && !(arrival_time && service_staff)) return "已收款未派单"
})

// 修改确认订单方法
const handleConfirmOrder = async () => {
  try {
    // 获取当前选中的员工ID列表
    const selectedRows = tableRef.value.getSelectionRows()
    const selectedIds = selectedRows.map((row: any) => row.id)
    
    // 获取日期和档期
    const date = getSelectedDate.value
    const timeSlot = selectTimeResult.value
    
    // 构建请求数据
    const requestData = {
      expectedTime: `${date} ${timeSlot}`,
      staffIds: selectedIds
    }
    
    // 调用后端接口
    const resp = await instance.put(`/api/order/updateSchedule/${id}`, requestData)
    
    if (resp.status === 200) {
      ElMessage.success('订单更新成功')
      // 更新本地数据
      customerInfo.arrival_time = requestData.expectedTime
      customerInfo.staffIds = selectedIds
      // 返回订单管理页面
      router.push({name:'order.default'})
    }
  } catch (error) {
    ElMessage.error('订单更新失败')
  }
}

// 在 script 部分添加计算属性
const getSelectedDate = computed(() => {
  if (customerInfo.arrival_time) {
    return customerInfo.arrival_time.split('下午')[0].split('上午')[0]
  }
  return customerInfo.expected_time.split('下午')[0].split('上午')[0]
})

const getSelectedTime = computed(() => {
  if (customerInfo.arrival_time) {
    return customerInfo.arrival_time.includes('下午') 
      ? '下午' + customerInfo.arrival_time.split('下午')[1]
      : '上午' + customerInfo.arrival_time.split('上午')[1]
  }
  return '未分配'
})

const isStaffSelected = (staffId: number) => {
  return customerInfo.staffIds?.includes(staffId)
}

const showDistanceDetail = (staff: any) => {
  staffSelectStore.mapDetail = true
  // 设置当前选中的员工位置
  const staffIndex = staffSelectStore.gridData.findIndex((item: any) => item.id === staff.id)
  if (staffIndex !== -1) {
    staffSelectStore.resultLocation = staffSelectStore.location[staffIndex]
  }
}

const tableRef = ref()

onMounted(async () => {
  const resp = await instance.get(`/api/order/orderDetail/${id}`)
  const staffStore = useStaffStore()
  const { data } = resp
  const result = {
    customer_name: data.customer_name,
    address: data.address,
    phone: data.phone,
    customer_type: data.customer_type,
    room_attributes: data.room_attributes,
    service_type: data.service_type,
    price: data.price,
    risk_money: data.risk_money,
    expected_time: data.expected_time,
    tags: data.tags,
    remark: data.remark,
    record_time: data.record_time,
    order_number: data.order_number,
    arrival_time: data.arrival_time,
    service_staff: data.service_staff,
    pay_status: data.pay_status,
    staffIds: data.staffIds || []
  }
  Object.assign(customerInfo, result)
  
  // 如果有已分配的上门时间，更新选择结果
  if (data.arrival_time) {
    const timePart = data.arrival_time.includes('下午') 
      ? '下午' + data.arrival_time.split('下午')[1]
      : '上午' + data.arrival_time.split('上午')[1]
    selectTimeResult.value = timePart
  }

  // 修改数据加载逻辑
  if (staffSelectStore.gridData.length === 0) {
    await staffStore.fetchStaffList()
    staffSelectStore.gridData = [...staffStore.availableStaffList]
    
    // 为每个员工生成位置信息
    staffSelectStore.gridData.forEach(() => {
      staffSelectStore.location.push(staffSelectStore.createLocation())
    })
    
    // 计算距离
    await staffSelectStore.distanceCalculate(customerInfo.address, staffSelectStore.location)
  }

  // 在数据加载完成后，设置选中状态
  nextTick(() => {
    if (tableRef.value && customerInfo.staffIds?.length) {
      // 先清除所有选中状态
      tableRef.value.clearSelection()
      // 保存 staffIds 的副本
      const staffIdsToSelect = [...customerInfo.staffIds]
      
      // 遍历所有行，选中对应的员工
      staffSelectStore.gridData.forEach((row: { id: number; }) => {
        if (staffIdsToSelect.includes(row.id)) {
          tableRef.value.toggleRowSelection(row, true)
        }
      })
    }
  })
})

// 添加选择变化处理方法
const handleSelectionChange = (selection: any[]) => {
  // 更新选中的员工ID列表
  const selectedIds = selection.map(item => item.id)
  customerInfo.staffIds = selectedIds
}

</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.card-title {
  font-weight: bold;
  color: #333;
}

.time-item {
  padding: 8px 15px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  text-align: center;
}

.selected-time {
  color: #666;
  font-size: 14px;
}
</style>